/**
 *
 */
package steven.gui.console;

import java.io.Serializable;

/**
 * @author steven.lam.t.f
 *
 */
public class ConsoleInputLine extends ConsoleLine implements Serializable{
	private static final long serialVersionUID = 8593156188196655134L;
	private int cursorPosition;
	private int cursorOffsetWidth;

	public ConsoleInputLine(){
		this.cursorPosition = 0;
		this.cursorOffsetWidth = 0;
	}
	public void insert(final char c){
		super.ensureCapacity(1);
		System.arraycopy(super.chars, this.cursorPosition, super.chars, this.cursorPosition + 1, super.length - this.cursorPosition);
		super.chars[this.cursorPosition++] = c;
		final int width = super.getWidth(c);
		super.lineWidth += width;
		super.length++;
		this.cursorOffsetWidth += width;
	}
	public void insert(final String s){
		super.append(s);
		int width = 0;
		for(int i = 0; i < s.length(); i++){
			width += super.getWidth(s.charAt(i));
		}
		this.cursorPosition += s.length();
		this.cursorOffsetWidth += width;
	}
	public void deletePreviousCharacter(){
		if(this.cursorPosition > 0){
			final char c = super.chars[this.cursorPosition - 1];
			final int width = super.getWidth(c);
			super.lineWidth -= width;
			System.arraycopy(super.chars, this.cursorPosition, super.chars, this.cursorPosition - 1, super.length - this.cursorPosition);
			this.cursorPosition--;
			super.length--;
			this.cursorOffsetWidth -= width;
		}
	}
	public void deleteNextCharacter(){
		if(this.cursorPosition < super.length){
			final char c = super.chars[this.cursorPosition];
			final int width = super.getWidth(c);
			super.lineWidth -= width;
			System.arraycopy(super.chars, this.cursorPosition + 1, super.chars, this.cursorPosition, super.length - this.cursorPosition - 1);
			super.length--;
		}
	}
	public void moveCursorBackwards(){
		if(this.cursorPosition > 0){
			final char c = super.chars[this.cursorPosition - 1];
			final int width = super.getWidth(c);
			this.cursorPosition--;
			this.cursorOffsetWidth -= width;
		}
	}
	public void moveCursorForwards(){
		if(this.cursorPosition < super.length){
			final char c = super.chars[this.cursorPosition];
			final int width = super.getWidth(c);
			this.cursorPosition++;
			this.cursorOffsetWidth += width;
		}
	}
	public void moveCursorToBeginning(){
		this.cursorPosition = 0;
		this.cursorOffsetWidth = 0;
	}
	public void moveCursorToEnd(){
		this.cursorPosition = super.length;
		this.cursorOffsetWidth = super.lineWidth;
	}
	@Override
	public void clear(){
		super.clear();
		this.cursorPosition = 0;
		this.cursorOffsetWidth = 0;
	}
	public final int getCursorOffsetWidth(){
		return this.cursorOffsetWidth;
	}
	public final int getCursorPosition(){
		return this.cursorPosition;
	}
}
